package com.example.wotu;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.UUID;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragBook.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragBook#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragBook extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private SQLiteDatabase sql;
    private View view;
    private Fragment fragbookml;
    private ListView gridbook;
    private LinearLayout insbook;
    private LinearLayout shuj;
    private ImageView bookdr;
    private ImageView inbook;
    private ImageView bookfw;
    private ImageView bookcun;
    private ImageView bookdel;
    private TextView bookbt;
    private EditText Insbookname;
    private EditText InsbookJs;
    private ArrayAdapter mAdapter;
    private FrameLayout fragml;
    private ArrayList<Integer> bookDataID;
    private ArrayList<String> bookData;
    private int InsORupd = 0,UIID = 0;

    public FragBook() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragBook.
     */
    // TODO: Rename and change types and number of parameters
    public static FragBook newInstance(String param1, String param2) {
        FragBook fragment = new FragBook();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //****** 105 ******
        view = inflater.inflate(R.layout.frag_book, container, false);
        mListener.onNOT_WK(101);
        UIID = mListener.usei();
        getFindV();
        getBookData();
        OnClickGrid();
        return view;
    }

    private void getFindV(){
        gridbook = (ListView) view.findViewById(R.id.GridBook);
        insbook = (LinearLayout)view.findViewById(R.id.Insbook);
        shuj = (LinearLayout)view.findViewById(R.id.shuj);
        bookdr = (ImageView)view.findViewById(R.id.bookDR);
        inbook = (ImageView)view.findViewById(R.id.Inbook);
        bookfw = (ImageView)view.findViewById(R.id.bookFW);
        bookcun = (ImageView)view.findViewById(R.id.bookCUN);
        bookdel = (ImageView)view.findViewById(R.id.bookdel);
        bookbt = (TextView)view.findViewById(R.id.bookBT);
        Insbookname = (EditText) view.findViewById(R.id.Insbookname);
        InsbookJs = (EditText) view.findViewById(R.id.InsbookJs);
        fragml = (FrameLayout) view.findViewById(R.id.fragml);
    }
    public void setVis(){
        shuj.setVisibility(View.GONE);
        insbook.setVisibility(View.GONE);
        fragml.setVisibility(View.GONE);
        bookdel.setVisibility(View.GONE);
    }
    public void getBookData(){
        getbooks();
        mAdapter = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,bookData);
        gridbook.setAdapter(mAdapter);
    }
    private void getbooks(){
        bookData = new ArrayList<>();
        bookDataID = new ArrayList<>();
        try{
            sql = new MySQLOpen(getActivity()).getReadableDatabase();
            Cursor cs = sql.rawQuery("select novelid,novelname from novel where useid = ? and fwl = ?",new String[]{String.valueOf(UIID),"0"});
            while (cs.moveToNext()){
                bookDataID.add(cs.getInt(0));
                bookData.add(cs.getString(1));
            }
            cs.close();
            sql.close();
        }catch (Exception e){
            e.printStackTrace();
            sql.close();
        }
    }
    private void JIANP(){
        //键盘问题
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    private void OnClickGrid(){
        gridbook.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                setVis();
                fragml.setVisibility(View.VISIBLE);
                fragbookml = new FragBookml();
                Bundle bu = new Bundle();
                bu.putInt("bookid",bookDataID.get(position));
                bu.putString("bookname",bookData.get(position));
                fragbookml.setArguments(bu);
                getChildFragmentManager().beginTransaction().replace(R.id.fragml,fragbookml).commitAllowingStateLoss();
            }
        });
        gridbook.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                setVis();
                insbook.setVisibility(View.VISIBLE);
                bookdel.setVisibility(View.VISIBLE);
                bookbt.setText("修改书籍信息");
                mListener.onNOT_WK(108);
                sql = new MySQLOpen(getActivity()).getReadableDatabase();
                try{
                    Cursor cs = sql.rawQuery("select novelname,noveljs from novel where novelid = ?",new String[]{String.valueOf(bookDataID.get(i))});
                    while (cs.moveToNext()){
                        Insbookname.setText(cs.getString(0));
                        InsbookJs.setText(cs.getString(1));
                        InsORupd = bookDataID.get(i);
                    }
                    sql.close();
                }catch (Exception e){
                    e.printStackTrace();
                    sql.close();
                }
                return true;
            }
        });
        inbook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setVis();
                insbook.setVisibility(View.VISIBLE);
                bookbt.setText("添加书籍信息");
                mListener.onNOT_WK(108);
                Insbookname.setText("");
                InsbookJs.setText("");
                InsORupd = 0;
            }
        });
        bookcun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Insbookname.getText().toString().trim().length()>0 && InsbookJs.getText().toString().length()>0){
                    sql = new MySQLOpen(getActivity()).getReadableDatabase();
                    try{
                        if(InsORupd > 0){
                            ContentValues cvl = new ContentValues();
                            cvl.put("novelname",Insbookname.getText().toString().trim());
                            cvl.put("noveljs",InsbookJs.getText().toString());
                            int l = sql.update("novel",cvl,"novelid = ?",new String[]{String.valueOf(InsORupd)});
                            if(l > 0){
                                JIANP();
                                setVis();
                                shuj.setVisibility(View.VISIBLE);
                                getBookData();
                                Toast.makeText(getActivity(),"修改成功！",Toast.LENGTH_SHORT).show();
                            }
                            else Toast.makeText(getActivity(),"修改失败！",Toast.LENGTH_SHORT).show();
                        }else{
                            ContentValues cvl = new ContentValues();
                            cvl.put("useid",UIID);
                            cvl.put("fwl",0);
                            cvl.put("novelpath",0);
                            cvl.put("novelname",Insbookname.getText().toString().trim());
                            cvl.put("noveljs",InsbookJs.getText().toString());
                            long l = sql.insert("novel",null,cvl);
                            sql.close();
                            if(l > 0){
                                setVis();
                                shuj.setVisibility(View.VISIBLE);
                                getBookData();
                                JIANP();
                                Toast.makeText(getActivity(),"添加完成！",Toast.LENGTH_SHORT).show();
                            }
                            else Toast.makeText(getActivity(),"添加失败！",Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        sql.close();
                    }
                }else Toast.makeText(getActivity(),"请填写完整所有信息！",Toast.LENGTH_SHORT).show();
            }
        });
        bookfw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setVis();
                shuj.setVisibility(View.VISIBLE);
                JIANP();
            }
        });
        bookdel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getActivity())
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("墨色提示：")
                        .setMessage("是否删除此本？")
                        .setNeutralButton("确认", new DialogInterface.OnClickListener() {     //左边
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                JIANP();
                                sqldelbook();
                                setVis();
                                shuj.setVisibility(View.VISIBLE);
                                getBookData();
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create().show();
            }
        });
        //导入
        bookdr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setVis();
                mListener.onNOT_WK(109);
                fragml.setVisibility(View.VISIBLE);
                fragbookml = new FragBookDR();
                getChildFragmentManager().beginTransaction().replace(R.id.fragml,fragbookml).commitAllowingStateLoss();
            }
        });
    }
    private void sqldelbook(){
        sql = new MySQLOpen(getActivity()).getReadableDatabase();
        try{
            sql.beginTransaction();
            Cursor cs = sql.rawQuery("select chapterid from chapter where novelid = ?",new String[]{String.valueOf(InsORupd)});
            if(cs.moveToFirst()){
                ArrayList<Integer> as = new ArrayList<>();
                do{
                    as.add(cs.getInt(0));
                }while (cs.moveToNext());
                for(int i=0;i<as.size();i++){
                    sql.delete("chapter","chapterid = ?",new String[]{String.valueOf(as.get(i))});
                }
            }
            int i = sql.delete("novel","novelid = ?",new String[]{String.valueOf(InsORupd)});
            if(i > 0){
                sql.setTransactionSuccessful();
                Toast.makeText(getActivity(),"删除完成！",Toast.LENGTH_SHORT).show();
            }
            else Toast.makeText(getActivity(),"删除失败！",Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getActivity(),"删除错误！",Toast.LENGTH_SHORT).show();
        }finally {
            sql.endTransaction();
            sql.close();
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onNOT_WK(int wk);
        int usei();
    }
}
